/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.giant.bean.transactions;

import com.giant.bean.parametrics.CatalogBean;
import com.giant.entities.WClaim;
import com.giant.entities.WClaimImage;
import com.giant.exceptions.OperacionInvalidaException;
import com.giant.services.IServicioPersistenciaLocal;
import com.giant.services.ServicioPersistencia;
import com.giant.services.transactions.ServiceClaimLocal;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.application.ViewHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author taticay
 */
@ManagedBean
@ViewScoped
public class ClaimBean implements Serializable {

    //CONSTANTES   
    public static final int TYPE_FRAME = 1;
    public static final int TYPE_CLAIM = 2;
    public static final int TYPE_GEAR = 3;
    //-----------------------------------------------------------
    // Atributos
    //-----------------------------------------------------------
    @EJB
    private ServiceClaimLocal serviceClaim;
    private int typeClaim;
    private Date start;
    private Date finish;
    private String claimNo;
    private String frameNo;
    private int claimItem;
    private ArrayList<byte[]> photoFrame = new ArrayList<byte[]>();
    private ArrayList<byte[]> photoClaim = new ArrayList<byte[]>();
    private ArrayList<byte[]> photoGears = new ArrayList<byte[]>();
    @ManagedProperty(value = "#{catalogBean}")
    private CatalogBean catalogBean;
    private String modelYear;
    private String modelName = " ";
    private List<WClaim> claims;
    WClaim temp = new WClaim();
    @EJB
    private IServicioPersistenciaLocal persistence;

    //-----------------------------------------------------------
    // Getters y setters
    //-----------------------------------------------------------
    public ClaimBean() {

        persistence = new ServicioPersistencia();
    }

    public int getClaimItem() {
        return claimItem;
    }

    public void setClaimItem(int claimItem) {
        this.claimItem = claimItem;
    }

    public String getModelName() {
        return modelName;
    }

    public void setModelName(String modelName) {
        this.modelName = modelName;
    }

    /**
     * Devuelve el objeto de vendedor actual
     *
     * @return vendedor Vendedor actual
     */
    public List<WClaim> getClaims() {

        if (claims == null) {
            claims = serviceClaim.getClaims();
        }
        return claims;
    }

    /**
     * Devuelve todos los vendedores del sistema
     *
     * @return vendedores Lista con todos los vendedores del sistema
     */
    public void filterCriteria() {

        String sql = "SELECT i FROM WClaim i where 1=1";

        if (claimNo != null && !claimNo.equals("")) {
            sql += " and i.idClaim=" + claimNo;
        }
        if (frameNo != null && !frameNo.equals("")) {
            sql += " and i.frameNo=" + frameNo;
        }

        if (start != null && finish != null) {

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String dateIni = format.format(start);
            String dateFin = format.format(finish);

            sql += " and i.dateClaim between {d '" + dateIni + "'} and {d '" + dateFin + "'}";

        }
        claims = persistence.executeObjectSql(sql);
    }

    public WClaim getTemp() {
        return temp;
    }

    public void setTemp(WClaim temp) {
        this.temp = temp;
    }

    public CatalogBean getCatalogBean() {
        return catalogBean;
    }

    public void setCatalogBean(CatalogBean catalogBean) {
        this.catalogBean = catalogBean;
    }

    public String createClaimFrame() {
        try {
            String sql = "INSERT INTO w_claim(`id_claim`, `id_catalog`, `id_class`, `id_line`, `id_brand`, `frame_no`, `frame_size`, `id_claim_item`, "
                    + "`claim_description`, `id_claim_status`, `warranty_order`, `date_claim`, `date_closed`, `date_confirm`, "
                    + "`height`, `weight`, `situation_desc`, `notes`,`sku`, `invoice_no`, `quantity` )"
                    + "select null, id_catalog, id_class, id_line, id_brand, '" + temp.getFrameNo() + "', '" + temp.getFrameSize() + "', " + claimItem + ", '"
                    + temp.getClaimDescription() + "', 1, null,sysdate(), null, null, " + temp.getHeight()
                    + ", " + temp.getWeight() + ", '" + temp.getSituationDesc() + "', null, " + temp.getSku() + ", " + temp.getInvoiceNo()
                    + ", " + temp.getQuantity() + " from in_catalog"
                    + " where model_year=" + getCatalogBean().getParam() + " and model_name='" + modelName + "'";

            serviceClaim.executeCRUDSQL(sql);

            sql = "SELECT ifnull(max(ID_CLAIM),0) as max FROM W_CLAIM";

            int IdClaim = Integer.parseInt(serviceClaim.executeSQL(sql).get(0) + "");

            for (int i = 0; i < photoFrame.size(); i++) {

                byte[] temp = photoFrame.get(i);
                WClaimImage tempo = new WClaimImage();
                tempo.setIdClaim(IdClaim);
                tempo.setIdTypeClaimImg(TYPE_FRAME);
                tempo.setImage(temp);
                try {
                    serviceClaim.addClaimImage(tempo);
                } catch (OperacionInvalidaException ex) {
                    System.out.println("error image bd");
                    Logger.getLogger(ClaimBean.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            for (int i = 0; i < photoClaim.size(); i++) {

                byte[] temp = photoClaim.get(i);
                WClaimImage tempo = new WClaimImage();
                tempo.setIdClaim(IdClaim);
                tempo.setIdTypeClaimImg(TYPE_CLAIM);
                tempo.setImage(temp);
                try {
                    serviceClaim.addClaimImage(tempo);
                } catch (OperacionInvalidaException ex) {
                    System.out.println("Error image bd");
                    Logger.getLogger(ClaimBean.class.getName()).log(Level.SEVERE, null, ex);
                }
            }


        } catch (Exception ex) {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Invalid data"));
        }
        //Limpiar datos
        refresh();
        return "";
    }

    public String createClaimGear() {
        try {
            String sql = "INSERT INTO w_claim(`id_claim`, `id_catalog`, `id_class`, `id_line`, `id_brand`, `frame_no`, `frame_size`, `id_claim_item`, "
                    + "`claim_description`, `id_claim_status`, `warranty_order`, `date_claim`, `date_closed`, `date_confirm`, "
                    + "`height`, `weight`, `situation_desc`, `notes`,`sku`, `invoice_no`, `quantity` )"
                    + "select null, null, null, null, null, '" + temp.getFrameNo() + "', '" + temp.getFrameSize() + "', (select id_claim_item from w_claim_item where is_gear=1), '"
                    + temp.getClaimDescription() + "', 1, null,sysdate(), null, null, " + temp.getHeight()
                    + ", " + temp.getWeight() + ", '" + temp.getSituationDesc() + "', null, " + temp.getSku() + ", " + temp.getInvoiceNo()
                    + ", " + temp.getQuantity() + " from dual";

            serviceClaim.executeCRUDSQL(sql);

            sql = "SELECT ifnull(max(ID_CLAIM),0) as max FROM W_CLAIM";

            int IdClaim = Integer.parseInt(serviceClaim.executeSQL(sql).get(0) + "");

            for (int i = 0; i < photoGears.size(); i++) {

                byte[] temp = photoGears.get(i);
                WClaimImage tempo = new WClaimImage();
                tempo.setIdClaim(IdClaim);
                tempo.setIdTypeClaimImg(TYPE_GEAR);
                tempo.setImage(temp);
                try {
                    serviceClaim.addClaimImage(tempo);
                } catch (OperacionInvalidaException ex) {
                    System.out.println("Error image bd");
                    Logger.getLogger(ClaimBean.class.getName()).log(Level.SEVERE, null, ex);
                }
            }


        } catch (Exception ex) {
            ex.printStackTrace();
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Invalid data"));
        }
        return "";
    }

    public void handleFileUpload(FileUploadEvent event) {
        if (photoFrame.size() < 2) {
            photoFrame.add(event.getFile().getContents());
        } else {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "You can only upload 2 photos for the fraim item!"));
        }
    }

    public void handleFileUpload2(FileUploadEvent event) {
        if (photoClaim.size() <= 4) {
            photoClaim.add(event.getFile().getContents());
        } else {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "You can only upload 4 photos for the claim item!"));
        }

    }

    public void handleFileUpload3(FileUploadEvent event) {
        if (photoGears.size() < 2) {
            photoGears.add(event.getFile().getContents());
        } else {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "You can only upload 2 photos for the gear item!"));
        }
    }

    public Date getStart() {
        return start;
    }

    public void setStart(Date start) {
        this.start = start;
    }

    public Date getFinish() {
        return finish;
    }

    public void setFinish(Date finish) {
        this.finish = finish;
    }

    public String getClaimNo() {
        return claimNo;
    }

    public void setClaimNo(String claimNo) {
        this.claimNo = claimNo;
    }

    public String getFrameNo() {
        return frameNo;
    }

    public void setFrameNo(String frameNo) {
        this.frameNo = frameNo;
    }

    public void refresh() {
        FacesContext context = FacesContext.getCurrentInstance();
        Application application = context.getApplication();
        ViewHandler viewHandler = application.getViewHandler();
        UIViewRoot viewRoot = viewHandler.createView(context, context
                .getViewRoot().getViewId());
        context.setViewRoot(viewRoot);
        context.renderResponse();
    }
}
